package com.decent.manager.system.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import com.decent.common.bo.SimpleMessage;
import com.decent.common.entity.manager.SystemUser;
import com.decent.common.enums.CommonStatusEnum;
import com.decent.common.enums.ErrorCodeEnum;
import com.decent.common.enums.manager.UserTypeEnum;
import com.decent.common.exception.ErrorCodeException;
import com.decent.manager.config.security.context.LoginContext;
import com.decent.manager.system.auth.service.impl.CleanAuthServiceImpl;
import com.decent.manager.system.auth.vo.LoginUser;
import com.decent.manager.system.dao.SystemUserDao;
import com.decent.manager.system.dao.SystemUserRoleDao;
import com.decent.manager.system.dto.SystemUserDTO;
import com.decent.manager.system.service.SystemUserService;
import com.decent.manager.system.vo.SystemUserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 账号实现
 *
 * @author wangyan
 **/
@Service
public class SystemUserServiceImpl implements SystemUserService {
    @Resource
    private CleanAuthServiceImpl cleanAuthService;
    @Resource
    private SystemUserDao systemUserDao;
    @Resource
    private LoginContext loginContext;
    @Resource
    private SystemUserRoleDao systemUserRoleDao;

    /**
     * 根据手机号查询用户信息
     *
     * @param mobile 手机号
     * @return 用户信息
     */
    @Override
    public SystemUser queryUserByMobile(String mobile) {
        return systemUserDao.queryUserByMobile(mobile);
    }

    /**
     * 更新登录信息
     *
     * @param principal 登录信息
     */
    @Override
    public void updateUserById(LoginUser principal) {
        systemUserDao.updateUserById(principal);
    }

    /**
     * 分页查询
     *
     * @param user 查询条件
     * @return page
     */
    @Override
    public PageInfo<SystemUserVO> queryPage(SystemUserDTO user) {
        PageHelper.startPage(user.getPageNumber(), user.getPageSize());
        return new PageInfo<>(systemUserDao.queryPage(user));
    }

    /**
     * 创建员工
     *
     * @param user 新增信息
     * @return SimpleMessage
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SystemUserVO createUser(SystemUserDTO user) {
        if (BooleanUtil.isTrue(systemUserDao.queryRepeatUser(user))) {
            throw new ErrorCodeException(ErrorCodeEnum.INVALID_PARAMS, "登录账号或手机号已存在，请更换登录账号并核实手机号");
        }
        // 随机登录密码
        String defaultLoginPassword = RandomUtil.randomNumbers(8);
        user.setLoginPassword(BCrypt.hashpw(defaultLoginPassword, BCrypt.gensalt()));
        user.setCreator(loginContext.getLoginUserName());
        user.setUserType(UserTypeEnum.NORMAL);
        user.setUserStatus(CommonStatusEnum.NORMAL);
        // 创建账号
        systemUserDao.createUser(user);
        // 绑定角色
        systemUserRoleDao.createUserRole(user);
        SystemUserVO newUser = new SystemUserVO();
        newUser.setMobile(user.getMobile());
        newUser.setLoginPassword(defaultLoginPassword);
        return newUser;
    }

    /**
     * 修改
     *
     * @param user 修改信息
     */
    @Override
    public SimpleMessage updateUser(SystemUserVO user) {
        if (Objects.isNull(user.getUserAccount())) {
            return new SimpleMessage(ErrorCodeEnum.INVALID_PARAMS);
        }
        SystemUser systemUser = systemUserDao.queryUserByAccount(user.getUserAccount());
        user.setId(systemUser.getId());
        if (Objects.nonNull(user.getRoleId())) {
            systemUserDao.updateUserRole(user);
        }
        if (Objects.nonNull(user.getUserName()) || Objects.nonNull(user.getMobile())) {
            SystemUser exist = systemUserDao.queryUserByMobile(user.getMobile());
            if (exist != null && !Objects.equals(systemUser.getMobile(), user.getMobile())) {
                return new SimpleMessage(ErrorCodeEnum.INVALID_PARAMS, "手机号已存在，请核实手机号");
            }
            systemUserDao.updateUser(user);
        }
        LoginUser loginUser = loginContext.getLoginUser();
        if (!loginUser.getUserAccount().equals(user.getUserAccount())) {
            cleanAuthService.clearLoginUserCache(user);
        }
        return new SimpleMessage(ErrorCodeEnum.OK);
    }

    /**
     * 重置密码
     *
     * @param user 账户信息
     * @return SimpleMessage
     */
    @Override
    public SystemUserVO resetPassword(SystemUserVO user) {
        if (!loginContext.isSuperAdmin()) {
            throw new ErrorCodeException(ErrorCodeEnum.ILLEGAL_AUTHORIZE);
        }
        LoginUser loginUser = loginContext.getLoginUser();
        if (loginUser.getUserAccount().equals(user.getUserAccount())) {
            throw new ErrorCodeException("不可重置当前登录账号的密码");
        }
        // 随机登录密码
        String defaultLoginPassword = RandomUtil.randomNumbers(8);
        user.setLoginPassword(BCrypt.hashpw(defaultLoginPassword, BCrypt.gensalt()));
        systemUserDao.setPassword(user);
        SystemUserVO newUser = new SystemUserVO();
        newUser.setUserAccount(user.getUserAccount());
        newUser.setLoginPassword(defaultLoginPassword);
        return newUser;
    }

    /**
     * 修改密码
     *
     * @param user 账户信息
     * @return SimpleMessage
     */
    @Override
    public SimpleMessage updatePassword(SystemUserVO user) {
        LoginUser loginUser = loginContext.getLoginUser();
        SystemUser userByAccount = systemUserDao.queryUserByAccount(loginUser.getUserAccount());
        SystemUserVO newUser = new SystemUserVO();
        newUser.setUserAccount(loginUser.getUserAccount());
        newUser.setLoginPassword(BCrypt.hashpw(user.getLoginPassword(), BCrypt.gensalt()));
        systemUserDao.setPassword(newUser);
        cleanAuthService.clearLoginUserCache(userByAccount);
        return new SimpleMessage(ErrorCodeEnum.OK);
    }
}
